package com.siyoumi.service;

import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.entity.SysLog;
import com.siyoumi.mapper.SysLogMapper;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.util.XStr;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


//t_s_log
@Service
public class SysLogService
        extends ServiceImplBase<SysLogMapper, SysLog> {
    static public SysLogService getBean() {
        return XSpringContext.getBean(SysLogService.class);
    }

    /**
     * 添加系统报错日志
     *
     * @param errmsg
     * @param errInfo
     */
    public SysLog addSysErrorLog(String errmsg, String errInfo) {
        InputData inputData = InputData.fromRequest();
        //String token = XHttpContext.getHttpServletRequest().getHeader("token");
        //inputData.put("token", token);
        //请求参数，包含post
        List<String> requestParamArr = new ArrayList<>();
        for (Map.Entry<String, Object> entry : inputData.entrySet()) {
            requestParamArr.add(entry.getKey() + "=" + entry.getValue());
        }
        String requestParam = "";
        if (requestParamArr.size() > 0) {
            requestParam = requestParamArr.stream().collect(Collectors.joining("&"));
        }

        return addSysLog("error", errmsg, errInfo, requestParam);
    }

    /**
     * 添加系统日志
     *
     * @param type         error:系统报错日志
     * @param errmsg
     * @param errInfo
     * @param requestParam
     */
    public SysLog addSysLog(String type, String errmsg, String errInfo, String requestParam) {
        SysLog entityLog = new SysLog();
        entityLog.setLog_type("sys");
        entityLog.setLog_type_sub(type);
        entityLog.setLog_x_id(XHttpContext.getX());
        entityLog.setLog_str_00(XStr.maxLen(errmsg, 300));
        entityLog.setLog_txt_00(XStr.maxLen(errInfo, 5000));
        entityLog.setLog_str_01(XStr.maxLen(requestParam, 200));
        entityLog.setAutoID();
        save(entityLog);

        return entityLog;
    }
}
